﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using PJ.Data.WCF;
using PJ.Framework;

namespace PJ.Data
{
    public abstract class EntityWCFProxyProvider<C, S, D, I> : ObjectWCFProxyProvider<C, S, D, I>, IEntityProvider<I>
        where I : class, IEntityData
        where D : BaseEntityData, I, new()
        where S : class, IEntityWCFProvider<D>
        where C : EntityProviderClient<S, D>, new()
    {


        protected EntityWCFProxyProvider(IObjectDataCache<I> cache)
            : base(cache)
        {
        }

        public I GetById(string id, GetDataMode mode)
        {
            if (id == null || id == "")
                throw new ArgumentNullException();
            I entity = null;
            if (Cache != null && (mode & GetDataMode.UseCache) == GetDataMode.UseCache)
                entity = Cache.FindById(id);
            if (entity == null)
            {
                try
                {
                    entity = ClientBase.GetById("", id, (int)mode) as I;
                    if (entity != null && Cache != null)
                        Cache.Add(entity);
                }
                catch (Exception ex)
                {
                    ClientBase = null;
                    ExceptionManager.Handle(ex);
                    throw;
                }
            }
            else
                return entity;
            if (entity == null && (mode & GetDataMode.Find) != GetDataMode.Find)
                throw new DataNotFoundException("id", id);
            return entity;
        }
        #region Interface override
        IEntityData IEntityProvider.GetById(string id, GetDataMode mode)
        {
            return GetById(id, mode);
        }

        #endregion
        #region Protected

        new protected IEntityCache<I> Cache
        {
            get { return (IEntityCache<I>)base.Cache; }
        }

        #endregion

        #region Field


        #endregion
    }
}
